import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from 'src/store'
import { getToken } from 'src/utils/auth'
import Router from "src/router/index";
const service = axios.create({
    baseURL: import.meta.env.VITE_BASE_API,
    timeout: 30000 // 设置请求超时的时长 5秒
})

service.interceptors.request.use(
    config => {
        if (config.url !== '/auth/login' && store.getters.token) {
            config.headers.RdAuthorization = getToken()
        }
        if (config.type && config.type == 'export') {
            config.responseType = 'arraybuffer';
        }
        return config
    },
    error => {
        console.error(error)
        return Promise.reject(error)
    }
)

service.interceptors.response.use(
    response => {
        let res = response.data
        let contentType = response.headers['content-type']
        if (response.headers['content-type'].indexOf('application/vnd.ms-excel;charset=utf-8') > -1) {
            const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
            const a = document.createElement('a')
            let href = window.URL.createObjectURL(blob)
            a.href = href
            let fileName = response.headers['content-disposition'].split(';')[1].split('=')[1].split('.')[0]
            a.download = decodeURIComponent(fileName)
            document.body.appendChild(a)
            a.click()
            document.body.removeChild(a)
            window.URL.revokeObjectURL(href)
        } else {
            //导出为空时不导出文件，返回错误提示
            if (response.headers['response-type'] == 'arraybuffer') {
                var encodedString = String.fromCharCode.apply(null, new Uint8Array(res));
                let decodedString = decodeURIComponent(escape(encodedString))
                console.log(decodedString)
                res = JSON.parse(decodedString);
            } else if (contentType == 'application/zip') {
                let blob = new Blob([response.data], { type: 'application/zip' })
                let url = window.URL.createObjectURL(blob)
                const link = document.createElement('a') // 创建a标签
                link.href = url
                link.download = '' // 重命名文件
                link.click()
                window.URL.revokeObjectURL(url) // 释放内存

                return new Promise(resolve => {
                    resolve({ success: true })
                })
            }

            if (res.code !== 20000) {
                if (res.code === 401) {
                    MessageBox.confirm('你已经退出了，你可以取消以保持在这个页面上，或者重新登录。', '确认注销', {
                        confirmButtonText: '重新登录',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        store.dispatch('user/resetToken').then(() => {
                            location.reload()
                        })
                    })
                } else {
                    Message.closeAll()
                    Message({
                        message: res.message || 'Error',
                        type: 'error',
                        center: true,
                        duration: 2 * 1000
                    })
                }
                return Promise.reject(new Error(res.message || 'Error'))
            }
            return res
        }
    },
    error => {
        let msg = error.message;
        try {
            msg = error.response.data.message;
        } catch (e) {
        }
        Message.closeAll()
        Message.error({
            message: msg,
            type: 'error',
            center: true,
            duration: 2 * 1000
        });

        if (error.response) {
            // 超时退出登录
            if (error.response.status == 401) {
                Router.push({ path: "/login" });
            }
            if (error.response.data && error.response.data.message) {
                error.message = error.response.data.message
            }
        }

        return Promise.reject(error)
    }
)

export default service
